package tecpointbenchmark.model;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Class handling the timer
 * 
 * @author Patrik
 **/
public class RunManager {
	private Timer timer;
	private ModuleHandler moduleHandler;

	/**
	 * Default constructor
	 * 
	 * @param mh
	 *            The active ModuleHandler
	 */
	public RunManager(ModuleHandler mh) {
		this.moduleHandler = mh;
	}

	/**
	 * RunManager.startTimer() Starts a timer.
	 * 
	 * @param timer
	 *            , how long the timer should run in milliseconds.
	 **/
	public void startTimer(long time) {
		timer = new Timer();

		try {
			// When time is up call SignalBenchmark
			timer.schedule(new SignalBenchmark(), time);
		} catch (IllegalArgumentException e) {
			System.out.println(e.getMessage());
		} catch (IllegalStateException e) {
			System.out.println(e.getMessage());
		}
	}

	/**
	 * RunManager.stopTimer() Stops the timer.
	 * 
	 */
	public void stopTimer() {
		timer.cancel();
	}

	/**
	 * Class RunManager.SignalBenchmark Unless someone has called
	 * Runmanager.stopTimer() this class will signal
	 * ModuleHandler.stopBenchmark() that the time is up.
	 * */
	private class SignalBenchmark extends TimerTask {
		public void run() {
			if (tecpointbenchmark.startup.Main.debug) {
				System.out
						.println("RunManager calls stopBenchmark() in ModuleHandler.");
			}
			moduleHandler.stopBenchmark(true);
		}
	}
}
